package io.github.ali.commons.util;

import java.util.function.Function;
import java.util.function.Supplier;

import org.apache.commons.lang3.StringUtils;

/**
 * 断言工具
 * @author bailey
 * @date 2021年9月17日
 */
public final class Asserts {
	/**************** if false throw ****************/
	public static void check(boolean ifSuccess) {
		if (!ifSuccess)
			throw new IllegalStateException();
	}

	public static void check(boolean ifSuccess, String message) {
		if (!ifSuccess)
			throw new IllegalStateException(message);
	}
	
	public static void check(boolean ifSuccess, RuntimeException exception) {
		if (!ifSuccess)
			throw exception;
	}

	public static void check(boolean ifSuccess, Supplier<RuntimeException> exceptionSupplier) {
		if (!ifSuccess)
			throw exceptionSupplier.get();
	}
	public static void check(boolean ifSuccess, Function<Object,RuntimeException> exceptionFunction,Object...exceptionFunctionParams) {
		if (!ifSuccess)
			throw exceptionFunction.apply(exceptionFunctionParams.length == 0 ? null : exceptionFunctionParams[0]);
		
	}
	/**************** if true throw ****************/
	public static void checkRev(boolean ifFailed) {
		if (ifFailed)
			throw new IllegalStateException();
	}

	public static void checkRev(boolean ifFailed, String message) {
		if (ifFailed)
			throw new IllegalStateException(message);
	}
	
	public static void checkRev(boolean ifFailed, RuntimeException exception) {
		if (ifFailed)
			throw exception;
	}

	public static void checkRev(boolean ifFailed, Supplier<RuntimeException> exceptionSupplier) {
		if (ifFailed)
			throw exceptionSupplier.get();
	}
	/**************** if null throw ****************/
	public static void notNull(Object object) {
		notNull(object, null);
	}

	public static void notNull(Object object, String field) {
		if (object == null)
			throw new NullPointerException(StringUtils.isBlank(field) ? "空指针异常" : field + "不能为Null");
	}

	/**************** if blank throw ****************/
	public static void notBlank(String str) {
		notBlank(str, null);
	}

	public static void notBlank(String str, String field) {
		if (StringUtils.isEmpty(str))
			throw new RuntimeException(StringUtils.isBlank(field) ? "空字符串异常" : field + "不能为空");
	}

	/**************** if not number throw ****************/
	public static void beNumber(Object object) {
		beNumber(object, null);
	}

	public static void beNumber(Object object, String field) {
		notNull(object, field);
		if (!MatchingUtil.isNumeral(object.toString()))
			throw new NumberFormatException(StringUtils.isBlank(field) ? "非数值异常" : field + "只能是数字");
	}
}
